var _ = require('lodash');
var path = require('path');
var webpack = require('webpack');
var os = require('os');

// PostCSS
var precss = require('precss');
var autoprefixer = require('autoprefixer');

// Plugins
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var WebpackMd5Hash = require('webpack-md5-hash');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var HtmlWebpackHarddiskPlugin = require('./webpack/html-webpack-harddisk-plugin');
var HappyPack = require('happypack');
var happyThreadPool = HappyPack.ThreadPool({ size: 5 });

// 常量
const host = '127.0.0.1';
const port = '10086';
var contextDir = __dirname;
var outputDir = path.join(__dirname, 'dist');
var publicPath = 'http://' + host + ':' + port + '/static/desktop/';
var htmlFileDir = './dev';

if (process.env.NODE_ENV == 'production') {
  publicPath = '/static/desktop/dist/';
  htmlFileDir = './';
}

var config = {
  context: contextDir,
  entry: {
    vendor: [
      'react', 'react-dom', 'react-router', 'classnames',
      'redux', 'redux-actions', 'react-redux', 'jquery', 'lodash', 'moment',
    ],
    note: [
      './applications/note/index.js'
    ],
  },
  output: {
    path: outputDir,
    publicPath: publicPath,
    filename: "[name]-[hash:5].js"
  },
  module: {
    loaders: [
      {
        test: /\.(js|jsx)$/,
        loader: 'babel',
        query: {
          presets: ['es2015', 'stage-0', 'stage-1', 'stage-2', 'stage-3', 'react'],
          plugins: ['transform-decorators-legacy', 'transform-function-bind'],
          compact: true,
          comments: false,
          cacheDirectory: true
        },
        happy: { id: 'js' }
      }, {
        test: /\.json$/,
        loader: 'json'
      }, {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract('style', 'css?sourceMap!postcss')
      }, {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract('style', 'css?sourceMap!postcss!less?sourceMap'),
        happy: { id: 'less' }
      },
      { test: /\.(png|jpe?g|gif|svg|ico)(\?\S*)?$/, loader: 'file?name=imgs/[name]-[hash:5].[ext]' },
      { test: /\.(woff|woff2|ttf|eot|ttc)(\?\S*)?$/, loader: 'file?name=fonts/[name]-[hash:5].[ext]' },
      { test: /\.(mp4|mpeg|webm|ogv|swf)(\?\S*)?$/, loader: 'file?name=video/[name]-[hash:5].[ext]' }
    ]
  },
  postcss: function () { return [precss, autoprefixer]; },
  resolve: {
    extensions: ['', '.js', '.jsx'],
    modulesDirectories: ['node_modules']
  },
  plugins: [

    new HappyPack({ id: 'js', threadPool: happyThreadPool, threads: 4, }),

    // 用文件的md5替换chunkhash，以避免共用js内容未变化时hash变化。
    new WebpackMd5Hash(),

    new webpack.DefinePlugin({
      PRODUCTION: JSON.stringify(process.env.NODE_ENV == 'production'),
    }),

    new webpack.optimize.CommonsChunkPlugin({ name: "vendor", minChunks: Infinity, }),

    // 有错误时不刷新页面
    new webpack.NoErrorsPlugin(),

    new webpack.ProvidePlugin({
      _: "lodash",
      $: "jquery",
      moment: 'moment'
    }),

    // 给js中剥离的css的文件指定名称
    new ExtractTextPlugin('[name]-[contenthash:5].css'),

    new HtmlWebpackPlugin({
      title: 'WNote',
      filename: htmlFileDir + '/note.html',
      template: './templates/note.html',
      alwaysWriteToDisk: true,
      chunks: ['vendor', 'note']
    }),

    new HtmlWebpackHarddiskPlugin({ outputDir: path.join(path.dirname(path.dirname(__dirname)), 'templates') })
  ],
  devServer: {
    contentBase: contextDir,
    port: port,
    host: host,
    inline: false,
    colors: true,
    console: true,
    global: true,
    process: true,
  }
};


if (process.env.NODE_ENV == 'production') {
  delete config.devtool;
  delete config.devServer;
  config.plugins = [
    new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } })
  ].concat(config.plugins);
}

module.exports = config;
